package com.ffs.template.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * xml解析工具
 *
 * @author ffs80
 */
@SuppressWarnings("unused")
public class XmlUtil {

    private static Document document;

    static {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            File xmlFile = new File("config/package.xml");
            document = builder.parse(xmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取包名或者作者
     */
    public static String getPackageOrAuthor(int type, String attr) {
        String packageName = "";
        String tagName = getTagName(type);
        Element element = document.getDocumentElement();
        NodeList nodeList = document.getElementsByTagName(attr);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node item = nodeList.item(i);
            Node parentNode = item.getParentNode();
            if (tagName.equals(parentNode.getNodeName())) {
                packageName = item.getTextContent();
            }
        }
        return packageName;
    }


    /**
     * 获取xml标签名
     *
     * @param type 类型
     */
    private static String getTagName(int type) {
        String tageName = "";
        switch (type) {
            case 0:
                tageName = "entity";
                break;
            case 1:
                tageName = "mapper";
                break;
            case 2:
                tageName = "iservice";
                break;
            case 3:
                tageName = "service";
                break;
            default:
        }
        return tageName;
    }
}
